package com.util;

import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;


@WebListener
public class OnlineUserNumberListener implements HttpSessionListener, HttpSessionAttributeListener{

	private int num; // 统计在线人数

	public OnlineUserNumberListener() {

	}

	public void sessionCreated(HttpSessionEvent se) {
		// 会话创建时，人数+1
		num++;
		ServletContext context = se.getSession().getServletContext();
		// 将在线人数存入应用域属性
		context.setAttribute("onlineUserNum", num);
//		System.out.println(num);
	}

	/**
	 * �Ự����ʱ�ļ�������
	 */
	public void sessionDestroyed(HttpSessionEvent se) {
		// 会话销毁时，人数减1
		num--;
		ServletContext context = se.getSession().getServletContext();
		
		context.setAttribute("onlineUserNum", num);
	}

	@Override
	public void attributeAdded(HttpSessionBindingEvent arg0) {
		System.out.println("attributeAdded");
		
	}

	@Override
	public void attributeRemoved(HttpSessionBindingEvent arg0) {
		System.out.println("attributeRemoved");
		
	}

	@Override
	public void attributeReplaced(HttpSessionBindingEvent arg0) {
		System.out.println("attributeReplaced");
		
	}

}
